#include <string.h>
#include <iostream>

using std::cout;
using std::endl;

class Computer
{
public:
    Computer(){ 
        cout << "Computer()" << endl;   
        _brand = nullptr;//本质上是赋值语句
        _price = 0;
    }

    Computer(const char * brand, double price)
    {
        cout << "Computer(const char*, double)" << endl;
        //开辟的是堆空间的字符串
        _brand = new char[strlen(brand) + 1]();
        strcpy(_brand, brand);
        _price = price;
    }

    Computer(const Computer & rhs)
    : _brand(new char[strlen(rhs._brand) + 1]())
    , _price(rhs._price)
    {
        cout << "Computer(const Computer &)" << endl;
        strcpy(_brand, rhs._brand);
    }

    //系统提供的赋值运算符函数不再满足需求
    //Computer & operator=(const Computer & rhs)
    //{
    //    cout << "operator=()" << endl;
    //    this->_brand = rhs._brand;
    //    this->_price = rhs._price;

    //    return *this;
    //}
    
    Computer & operator=(const Computer & rhs) {
        cout << "operator=()" << endl;
        //&rhs  这是对rhs对象取地址
        if(this != &rhs){//自赋值
            delete [] _brand;
            _brand = new char[strlen(rhs._brand) + 1]();
            strcpy(_brand, rhs._brand);
            _price = rhs._price;
        }
        return *this;
    }

    ~Computer()
    {   
        cout << "~Computer()" << endl;  
        if(_brand) {
            delete [] _brand;//回收一个数组
            _brand = nullptr;
        }
    }

    void print() 
    {
        if(_brand) {
            cout << "brand:" << _brand << endl;
            cout << "price:" << _price << endl;
        }
    }

private:
    char * _brand;//64位系统一个指针占据的空间是8个字节
    double _price;
};

int main()
{
    Computer c1("Huawei", 6666);
    cout << "c1:" << endl;
    c1.print();
    cout << endl;

    Computer c2("Xiaomi", 7777);
    cout << "c2:" << endl;
    c2.print();

    cout << "\n执行完赋值操作以后:" << endl;
    c1 = c2;
    cout << "c1:" << endl;
    c1.print();
    cout << endl;

    cout << "----" << endl;

    c1 = c1;//自赋值
    cout << "c1:" << endl;
    c1.print();
    cout << endl;

    return 0;
}

